import axios from 'axios';
import {ElMessage} from 'element-plus';
import {MUSIC_URLTYPE} from '@/constants/common-const';
import {useUserStore} from '@/store/system/user';


// token消息头
// const TOKEN_HEADER = 'x-access-token';
const TOKEN_HEADER = 'Authorization';


// 创建axios对象
const Axios = axios.create({
    // 添加proxy代理的key
    baseURL:import.meta.env.VITE_APP_API_KEY,
    // baseURL:'',
});

// ========================= 请求拦截器 =========================
Axios.interceptors.request.use(
    (config) => {
        if(config.urlType === MUSIC_URLTYPE) {
            // 添加proxy代理的key
            config.baseURL = import.meta.env.VITE_APP_CLOUDMUSIC_API_KEY;
            config.withCredentials = true;
            return config;
        };
        const token = useUserStore().token;
        if(token) {
            // 每次请求的时候携带token
            config.headers[TOKEN_HEADER] = token;
        }else {
            delete config.headers[TOKEN_HEADER];
        };
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

// ========================= 响应拦截器 =========================
Axios.interceptors.response.use(
    (response) =>{
        const res = response.data; // 对响应数据做点什么
        if(res.code && res.code != 200) {
            // 401 token错误 4001已在别处登录
            if(res.code === 401 || res.code === 4001) {
                // 重置用户缓存信息
                useUserStore().$reset();
                // localClear();
                // sessionClear();
                return Promise.reject(response);
            };
            ElMessage({
                showClose: true,
                message: res.msg,
                type: 'error'
            });
            return Promise.resolve(res);
        } else {
            return Promise.resolve(res);
        }
    },
    (error) => {
        // 对响应错误做点什么
        if (error.message.indexOf('timeout') != -1) {
            ElMessage({
                showClose: true,
                message: '网络超时',
                type: 'error'
            });
        } else if (error.message == 'Network Error') {
            ElMessage({
                showClose: true,
                message: '网络连接错误',
                type: 'error'
            });
        } else if(error.response.status == '401' && error.response.statusText == 'Unauthorized') {
            useUserStore().$reset(); 
            // localClear();
            // sessionClear();
        } else if (error.message.indexOf('Request') != -1) {
            ElMessage({
                showClose: true,
                message: '网络发生错误',
                type: 'error'
            });
        };
        return Promise.reject(error);
    }
);

// ========================= 对外提供方法，get和post，下载download等 =========================/**
/* 
* 通用请求封装
* @param config
*/
export const request = (config) => {
    return Axios.request(config);
};
 
/**
* post请求
*/
export const postRequest = (url, data, urlType, headers) => {
    return request({ 
        data, 
        url, 
        urlType,
        headers,
        method: 'post'
    });
};
 
/**
* get请求
*/
export const getRequest = (url, params, urlType, headers) => {
    return request({ 
        url, 
        params,
        urlType,
        headers,
        method: 'get', 
    });
};

/**
* delete请求 
* 
*/
export const deleteRequest = (url, params, urlType, headers) => {
   return request({ 
        url, 
        params,
        urlType,
        headers,
        method: 'delete'
    });
};

/**
 * 文件下载 
 * 
*/
const fileData = (result)=>{
    if (result.status === 200) {
        const blob = new Blob([result.data]); // 构造一个blob对象来处理数据，并设置文件类型
        const href = URL.createObjectURL(blob); //创建新的URL表示指定的blob对象
        const a = document.createElement("a"); //创建a标签
        a.style.display = "none";
        a.href = href; // 指定下载链接
        let describe = result.headers["content-disposition"];
        let file = describe.split(";");
        let fileNames = file[1].split("=");
        a.download = decodeURI(fileNames[1]); //指定下载文件名
        a.click(); //触发下载
        URL.revokeObjectURL(a.href); //释放URL对象
    }
}
